package com.aboo.pub.filter;

import java.io.IOException;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.filter.OncePerRequestFilter;

import com.aboo.pub.constant.ConfigXML;
import com.aboo.pub.constant.SessionConstant;
import com.aboo.pub.token.AdminLoginToken;
import com.aboo.util.SessionUtil;

/**
 * @author Yata Aboo
 * @Date 2012-10-17
 * @Desc 用于判断用户是否处于登陆状态的过滤器
 */
public class LoginTokenFilter extends OncePerRequestFilter {

	private static final Logger logger = Logger.getLogger(LoginTokenFilter.class);
	
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		if (uri.contains("/admin/")) {
			Object adminLoginToken = SessionUtil.getObject(request, SessionConstant.ADMIN_LOGIN_TOKEN);
			if (!checkAdmin(uri, ConfigXML.getAdminUnFilterSet())) {
				if (adminLoginToken == null) {
					logger.warn("用户访问后台页面" + uri + "时处于未登陆状态");
					String errorMsg = "您尚未登陆！";
					String redirectUrl = "admin/frameAction!login.do";
					request.setAttribute("errorMsg", errorMsg);
					request.setAttribute("redirectUrl", redirectUrl);
					String newUrl = "/error.jsp";
					request.getRequestDispatcher(newUrl).forward(request, response);
					return;
				}
				
				if (adminLoginToken != null && !((AdminLoginToken) adminLoginToken).containUrl(uri)) {
					logger.warn("用户访问后台页面" + uri + "时权限不足");
					String errorMsg = "您的访问权限不足！";
					request.setAttribute("errorMsg", errorMsg);
					String newUrl = "/error.jsp";
					request.getRequestDispatcher(newUrl).forward(request, response);
					return;
				}			
			}
		}
		if (uri.contains("/portal/")) {
			logger.warn("用户访问前台页面" + uri + "时处于未登陆状态");
			request.getRequestDispatcher("").forward(request, response);
			return;
		}
		filterChain.doFilter(request, response);
	}
	
	private boolean checkAdmin(String param, Set<String> set) {
		for (String str : set) {
			if (param.contains(str)) {
				return true;
			}
		}
		return false;
	}

}
